﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using MyMoviesBrowserLibrary;
using System.Data.Linq;
using System.Threading;
using System.ComponentModel;
using System.Windows.Threading;

namespace TVManager
{
    /// <summary>
    /// Interaction logic for ImportFolderWindow.xaml
    /// </summary>
    
    public partial class ImportFolderWindow : Window
    {
        private TVManagerBusinessLayer bl = new TVManagerBusinessLayer();
        private DirectoryInfo currentFolder;
        private Queue<DirectoryInfo> folderQueue;
        private BackgroundWorker worker;

        public ImportFolderWindow()
        {
            InitializeComponent();
            folderQueue = new Queue<DirectoryInfo>();
            browseButton.Click += new RoutedEventHandler(browseButton_Click);
            cancelButton.Click += new RoutedEventHandler(cancelButton_Click);
            importButton.Click += new RoutedEventHandler(importButton_Click);

            worker = new BackgroundWorker();
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);            
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);

            bl.DataUpdated += new UpdateEvent(bl_DataUpdated);

            worker.WorkerReportsProgress = true;
        }

        void bl_DataUpdated(string updateText)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate()
            {
                statusTextBox.Text += updateText + Environment.NewLine;
                statusTextBox.ScrollToEnd();
            });
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            int seriesId = (int)e.Argument;
            Series series = bl.AddSeries(seriesId, currentFolder.FullName);
            if (series != null)
                bl.UpdateEpisodeFiles(seriesId);
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate()
            {
                ProcessQueue();
            });            
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
        }

        void importButton_Click(object sender, RoutedEventArgs e)
        {
            cancelButton.IsEnabled = false;
            try
            {
                DirectoryInfo dir = new DirectoryInfo(folderTextBox.Text);
                if (!dir.Exists)
                {
                    MessageBox.Show("The entered folder does not exist. Please choose another folder.");
                    cancelButton.IsEnabled = false;
                    return;
                }

                if (rootCheckBox.IsChecked.HasValue && rootCheckBox.IsChecked.Value)
                {

                    MyMoviesBrowserDataContext ctx = bl.GetContext();
                    var q = ctx.Series.Select(s => s.FolderLocation).ToList();
                    foreach (DirectoryInfo dir2 in dir.GetDirectories())
                    {
                        if (!q.Contains(dir2.FullName))
                        {
                            folderQueue.Enqueue(dir2);
                        }
                    }
                }
                else
                    folderQueue.Enqueue(dir);
                ProcessQueue();
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }

        private void ProcessQueue()
        {
            if (folderQueue.Count > 0)
            {
                ImportFolder(folderQueue.Dequeue());                
            }
            else
                Close();
        }

        private void ImportFolder(DirectoryInfo folder)
        {
            currentFolder = folder;
            List<Series> series = bl.SearchForSeries(folder.Name);
            if (series.Count == 0)
            {
            }
            else if (series.Count == 1)
            {
                AddSeries(series.First().SeriesId);
            }
            else
            {
                ChooseSeriesWindow chooseSeries = new ChooseSeriesWindow();
                chooseSeries.Series = series;
                chooseSeries.SeriesSelected += new SeriesSelectedEvent(chooseSeries_SeriesSelected);
                chooseSeries.ShowDialog();
            }
        }

        void chooseSeries_SeriesSelected(object sender, int seriesId)
        {
            ChooseSeriesWindow chooseSeries = sender as ChooseSeriesWindow;
            if (chooseSeries != null)
                chooseSeries.Close();
            if (seriesId != 0)
                AddSeries(seriesId);
            else
                ProcessQueue();
        }


        void AddSeries(int seriesId)
        {
            worker.RunWorkerAsync(seriesId);
        }

        void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        void browseButton_Click(object sender, RoutedEventArgs e)
        {

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (!string.IsNullOrEmpty(Settings.Default.SavedRootFolder))
                dialog.SelectedPath = Settings.Default.SavedRootFolder;


            dialog.ShowNewFolderButton = true;


            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                folderTextBox.Text = dialog.SelectedPath;
                Settings.Default.SavedRootFolder = dialog.SelectedPath;
                Settings.Default.Save();
            }
        }
    }
}
